package com.zrrd._11_network.chatRoom;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;


/**
 * @author WanJl
 * @version 1.0
 * @title Client03
 * @description 客户端将本地文件上传到服务器
 * @create 2023/10/22 16:43
 */
public class ChatClient {

    private Socket socket;

    public ChatClient() throws Exception {
        //创建Socket对象，建立与服务器端的虚拟连接
        System.out.println("正在连接服务端...");
        socket = new Socket("localhost", 10010);
        System.out.println("已经和服务端建立联系");
    }

    /**
     * 启动客户端的方法
     */
    public void start() {
        try {
            Scanner scanner = new Scanner(System.in);
            //先要求用户创建一个昵称
            String username = null;
            while (true) {
                System.out.println("请用户输入用户名");
                username = scanner.nextLine();
                if (username.length() > 0) {
                    break;
                }
                System.out.println("输入有误");
            }
            System.out.println("欢迎你" + username + "!开始聊天吧！");
            /*socket 提供的方法：
             * OutputStream getOutStream
             * 获取一个字节输出流，通过该流写出的数据会被发送至远端计算机。
             */
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            //不能指明字节流,所以要加一个转换流，第二参数为true会行刷新
            PrintWriter pw = new PrintWriter(osw, true);
            //先将昵称发给服务器

            pw.println(username);

            /*
             * 启动读取服务端发送过来消息的线程
             */
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            /*
             * 将字符串发送至服务端，加上行刷新，说一句发一句
             * 否则需要用  flush()强制写出
             */
            while (true) {
                pw.println(scanner.nextLine());
                //pw.flush();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 该线程用来读取服务器端发送来的消息，并输出到客户端控制台显示
     */
    class ServerHandler implements Runnable {
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, "UTF-8");
                BufferedReader br = new BufferedReader(isr);

                String message = null;
                while ((message = br.readLine()) != null) {
                    System.out.println(message);
                }

            } catch (Exception e) {


            }
        }
    }


}